package inet.app.controller.service;

import inet.app.model.util.SmartLog;
import inet.app.view.activity.MyApp;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

import android.app.IntentService;
import android.content.Intent;
import android.text.TextUtils;

public class PushLiveService extends IntentService {

	public static final String RESULT = "result";
	public static final String NOTIFICATION = "inet.app.controller.service.receiver";

	private Socket mSocket;
	private boolean isRunning = true;

	public PushLiveService() {
		super("PushLiveService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		SmartLog.d("Start push live on service");
		mSocket = ((MyApp) getApplication()).get_socket();
		if (mSocket == null) {
			SmartLog.e("socket null, can't initialize service");
			return;
		}
		DataInputStream inputS = null;
		byte[] buff = null;
		int buffLength;
		int bs;
		String strResult = "";
		try {
			inputS = new DataInputStream(mSocket.getInputStream());
			SmartLog.d("push live input" + ((inputS == null) ? null : inputS
					.toString()));
			bs = inputS.available();
			while (isRunning) {
				while (bs > 0) {
					buff = new byte[bs];
					buffLength = buff.length;
					inputS.read(buff, 0, buffLength);
					strResult = strResult + new String(buff);
					SmartLog.d("push live " + strResult);
					if (strResult.endsWith("\r\n"))
						break;
				}
				SmartLog.d("length = 0");
			}
			if (strResult != null && !TextUtils.isEmpty(strResult.trim())) {
				publishResults(strResult);
			}
		} catch (IOException e) {
			SmartLog.e(e.toString());
			publishResults("error");
			return;
		}

	}

	private void publishResults(String result) {
		Intent intent = new Intent(NOTIFICATION);
		intent.putExtra(RESULT, result);
		sendBroadcast(intent);
	}

}
